import { 
  getInstructionsList, 
  getInstructionDetail, 
  addInstruction, 
  updateInstruction, 
  deleteInstruction,
  updatePrivacyClause,
  getPrivacyClause,
  addDataDocument,
  deleteDataDocument
} from '@/api/document'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      submitting: false,
      // 操作指南相关
      instructionsList: [],
      instructionDialogVisible: false,
      instructionDetailDialogVisible: false,
      instructionDialogTitle: '新增操作指南',
      currentInstruction: null,
      instructionForm: {
        id: null,
        title: '',
        content: '',
        imageUrl: '',
        image: null
      },
      instructionRules: {
        title: [
          { required: true, message: '请输入指南标题', trigger: 'blur' },
          { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入指南内容', trigger: 'blur' },
          { min: 10, max: 2000, message: '内容长度在 10 到 2000 个字符', trigger: 'blur' }
        ]
      },
      // 隐私条款相关
      privacyContent: '',
      privacyUploadUrl: '/dev-api/management/system/text/updatePrivacyClause',
      privacyUploadHeaders: {
        'Authorization': 'Bearer ' + getToken()
      },
      // 数据文档相关
      documentsList: [],
      documentDetailDialogVisible: false,
      currentDocument: null,
      uploadProgress: 0,
      dataUploadUrl: '/dev-api/management/system/text/add',
      dataUploadHeaders: {
        'Authorization': 'Bearer ' + getToken()
      }
    }
  },

  methods: {
    // ========== 操作指南相关方法 ==========
    
    // 加载操作指南列表
    async loadInstructionsList() {
      this.loading = true
      try {
        const response = await getInstructionsList()
        if (response.code === 1) {
          this.instructionsList = response.data || []
        } else {
          this.$message.error(response.msg || '加载失败')
        }
      } catch (error) {
        console.error('加载操作指南列表失败:', error)
        this.$message.error('加载操作指南列表失败')
      } finally {
        this.loading = false
      }
    },

    // 显示新增指南对话框
    showAddInstructionDialog() {
      this.instructionDialogTitle = '新增操作指南'
      this.instructionDialogVisible = true
    },

    // 编辑操作指南
    editInstruction(item) {
      this.instructionDialogTitle = '编辑操作指南'
      this.instructionForm = {
        id: item.id,
        title: item.title,
        content: item.content,
        imageUrl: item.img || ''
      }
      this.instructionDialogVisible = true
    },

    // 查看指南详情
    async viewInstructionDetail(item) {
      try {
        const response = await getInstructionDetail(item.id)
        if (response.code === 1) {
          this.currentInstruction = response.data
          this.instructionDetailDialogVisible = true
        } else {
          this.$message.error(response.msg || '获取详情失败')
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      }
    },

    // 删除操作指南
    deleteInstruction(item) {
      this.$confirm(`确定要删除操作指南"${item.title}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteInstruction(item.id)
          if (response.code === 1) {
            this.$message.success('删除成功')
            this.loadInstructionsList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      })
    },

    // 提交指南表单
    submitInstructionForm() {
      this.$refs.instructionForm.validate(async (valid) => {
        if (!valid) return
        
        this.submitting = true
        try {
          const submitData = {
            title: this.instructionForm.title,
            content: this.instructionForm.content,
            image: this.instructionForm.image
          }
          
          if (this.instructionForm.id) {
            submitData.id = this.instructionForm.id
          }
          
          const response = this.instructionForm.id 
            ? await updateInstruction(submitData)
            : await addInstruction(submitData)
            
          if (response.code === 1) {
            this.$message.success(this.instructionForm.id ? '更新成功' : '新增成功')
            this.instructionDialogVisible = false
            this.loadInstructionsList()
          } else {
            this.$message.error(response.msg || '操作失败')
          }
        } catch (error) {
          console.error('提交失败:', error)
          this.$message.error('操作失败')
        } finally {
          this.submitting = false
        }
      })
    },

    // 重置指南表单
    resetInstructionForm() {
      this.instructionForm = {
        id: null,
        title: '',
        content: '',
        imageUrl: '',
        image: null
      }
      this.$refs.instructionForm && this.$refs.instructionForm.resetFields()
    },

    // 图片上传前验证
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return false
    },

    // 图片选择变化
    handleImageChange(file, fileList) {
      if (file && file.raw) {
        this.instructionForm.image = file.raw
        this.instructionForm.imageUrl = URL.createObjectURL(file.raw)
      }
    },

    // 移除图片
    removeImage() {
      this.instructionForm.image = null
      this.instructionForm.imageUrl = ''
    },

    // ========== 隐私条款相关方法 ==========

    // 加载隐私条款内容
    async loadPrivacyContent() {
      this.loading = true
      try {
        const response = await getPrivacyClause()
        if (response.code === 1) {
          this.privacyContent = response.data
        } else {
          this.$message.error(response.msg || '加载失败')
        }
      } catch (error) {
        console.error('加载隐私条款失败:', error)
        this.$message.error('加载隐私条款失败')
      } finally {
        this.loading = false
      }
    },

    // 刷新隐私条款内容
    refreshPrivacyContent() {
      this.loadPrivacyContent()
    },

    // 隐私条款上传前验证
    beforePrivacyUpload(file) {
      const isMarkdown = file.type === 'text/markdown' || file.name.endsWith('.md')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isMarkdown) {
        this.$message.error('只能上传 Markdown 文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!')
        return false
      }
      return true
    },

    // 隐私条款上传成功
    handlePrivacyUploadSuccess(response, file) {
      if (response.code === 1) {
        this.$message.success('隐私条款更新成功')
        this.loadPrivacyContent()
      } else {
        this.$message.error(response.msg || '上传失败')
      }
    },

    // 隐私条款上传失败
    handlePrivacyUploadError(error) {
      console.error('上传失败:', error)
      this.$message.error('上传失败，请重试')
    },

    // 下载隐私条款内容
    downloadPrivacyContent() {
      if (!this.privacyContent) return
      
      const blob = new Blob([this.privacyContent], { type: 'text/markdown' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'privacy-clause.md'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },

    // ========== 数据文档相关方法 ==========

    // 加载数据文档列表
    async loadDocumentsList() {
      this.loading = true
      try {
        // 模拟数据，实际应该调用API
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.documentsList = [
          {
            id: 1,
            filename: 'psychological_questions_2024.json',
            size: 1024000,
            uploadTime: '2024-01-15T10:30:00',
            status: 'success',
            content: '{"questions": [{"id": 1, "question": "你最近感觉如何？", "options": ["很好", "一般", "不好"]}]}'
          },
          {
            id: 2,
            filename: 'user_behavior_data.json',
            size: 2048000,
            uploadTime: '2024-01-14T15:20:00',
            status: 'success',
            content: '{"behaviors": [{"action": "login", "timestamp": "2024-01-14T15:20:00"}]}'
          }
        ]
      } catch (error) {
        console.error('加载文档列表失败:', error)
        this.$message.error('加载文档列表失败')
      } finally {
        this.loading = false
      }
    },

    // 刷新数据文档列表
    refreshDocumentsList() {
      this.loadDocumentsList()
    },

    // 数据文档上传前验证
    beforeDataUpload(file) {
      const isJson = file.type === 'application/json' || file.name.endsWith('.json')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJson) {
        this.$message.error('只能上传 JSON 文件!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('文件大小不能超过 5MB!')
        return false
      }
      
      // 验证JSON格式
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          JSON.parse(e.target.result)
        } catch (error) {
          this.$message.error('JSON文件格式不正确!')
          return false
        }
      }
      reader.readAsText(file)
      
      return true
    },

    // 数据文档上传进度
    handleDataUploadProgress(event) {
      this.uploadProgress = Math.round((event.loaded / event.total) * 100)
    },

    // 数据文档上传成功
    handleDataUploadSuccess(response, file) {
      this.uploadProgress = 100
      if (response.code === 1) {
        this.$message.success('数据文档上传成功')
        this.loadDocumentsList()
        setTimeout(() => {
          this.uploadProgress = 0
        }, 1000)
      } else {
        this.$message.error(response.msg || '上传失败')
        this.uploadProgress = 0
      }
    },

    // 数据文档上传失败
    handleDataUploadError(error) {
      console.error('上传失败:', error)
      this.$message.error('上传失败，请重试')
      this.uploadProgress = 0
    },

    // 下载数据文档
    downloadDocument(document) {
      try {
        const blob = new Blob([document.content], { type: 'application/json' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = document.filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        this.$message.success('下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败')
      }
    },

    // 删除数据文档
    deleteDocument(document) {
      this.$confirm(`确定要删除文档"${document.filename}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteDataDocument(document.id)
          if (response.code === 1) {
            this.$message.success('删除成功')
            this.loadDocumentsList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      })
    },

    // 查看数据文档详情
    viewDocumentDetail(document) {
      this.currentDocument = document
      this.documentDetailDialogVisible = true
    },

    // ========== 通用工具方法 ==========

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 图片错误处理
    handleImageError() {
      console.log('图片加载失败')
    }
  }
}
